package erp_services

import (
	"errors"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/app/services/types"
	"xiehui-service/global"
)

type tphbOrderService struct {
}

type TpolQueryParams struct {
	TaskID   uint
	PageNum  int64
	PageSize int64
}

type TpolResult struct {
	List         []erp_models.TphbOrder
	TotalPages   int64
	TotalRecords int64
}

var TphbOrderService = new(tphbOrderService)

// 获取订单
func (orderTaskService *orderTaskService) TphbOrderList(params TpolQueryParams, pagination types.Pagination) (result *TpolResult, err error) {
	query := global.App.DB.Model(&erp_models.TphbOrder{})
	if params.TaskID > 0 {
		query = query.Where("task_id = ?", params.TaskID)
	}

	// 获取总记录数
	var totalRecords int64
	if err = query.Count(&totalRecords).Error; err != nil {
		return nil, err
	}

	// 设置分页查询条件
	offset := (pagination.PageNum - 1) * pagination.PageSize
	query = query.Order("ID DESC").Offset(int(offset)).Limit(int(pagination.PageSize))

	// 获取当前页记录数
	var currentTpos []erp_models.TphbOrder
	if err = query.Find(&currentTpos).Error; err != nil {
		return nil, err
	}

	// 计算总页数
	totalPages := (totalRecords + int64(pagination.PageSize) - 1) / int64(pagination.PageSize)

	return &TpolResult{
		List:         currentTpos,
		TotalPages:   totalPages,
		TotalRecords: totalRecords,
	}, nil
}

// 根据ID更新数据
func (tphbOrderService *tphbOrderService) GetById(task_id uint) (phbOrder erp_models.TphbOrder, err error) {
	if err = global.App.DB.Where("order_task_id = ?", task_id).First(&phbOrder).Error; err != nil {
		err = errors.New("未查询到信息")
		return erp_models.TphbOrder{}, err
	}

	return phbOrder, nil
}
